package wechat.base.snd.util;


import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.log4j.Logger;

//import sun.misc.IOUtils;
import org.apache.commons.io.IOUtils;

//import sun.misc.IOUtils;

public class ExecGet {
	final static Logger logger = Logger.getLogger(ExecGet.class.getName());

	public static String excuteGet(String path) throws Exception {
		String res = "";
		URL url = new URL(path);
		HttpURLConnection conn = (HttpURLConnection) url.openConnection();
		conn.setRequestMethod("GET");
		conn.setConnectTimeout(WeChatConf.WECHAT_URL_GET_TIME_OUT);
		InputStream inStream = conn.getInputStream();

		ByteArrayOutputStream outStream = new ByteArrayOutputStream();
		byte[] buffer = new byte[WeChatConf.WECHAT_URL_RESPONSE_BUFFER_SIZE];
		int len = 0;
		while ((len = inStream.read(buffer)) != -1) {
			outStream.write(buffer, 0, len);
		}
		res = outStream.toString("UTF-8");
		if (conn != null) {
			conn.disconnect();
		}
		return res;
	}
	public static File excuteGetImg(String url, String fileName) throws Exception {
		HttpClient httpClient = new DefaultHttpClient(); 
		HttpGet httpget = new HttpGet(url);
        HttpResponse response = httpClient.execute(httpget);
        HttpEntity entity = response.getEntity();
		File targetFile = new File(fileName);

		if (entity != null) {
		    InputStream inputStream = entity.getContent();
		    OutputStream outputStream = new FileOutputStream(targetFile);
		    IOUtils.copy(inputStream, outputStream);
		    outputStream.close();
		}
		return targetFile;
	}
}
